/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.deib.se2.meteocal.gui;

import au.com.bytecode.opencsv.CSVReader;
import it.polimi.deib.se2.meteocal.business.boundary.UserManager;
import it.polimi.deib.se2.meteocal.business.entity.Event;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.model.UploadedFile;

@Named
@RequestScoped
public class ImportExportBean {

    @EJB
    private UserManager um;
    
    @Inject
    private CalendarBean cb;
    
    private List<Event> events;
    private UploadedFile file;
   
    public ImportExportBean() {
    }
    
    @PostConstruct
    public void init() {
        setEvents((List<Event>) getUm().getLoggedUser().getCalendar().getEventCollection());
    }
    
    public void handleFileUpload() {
        FacesContext context = FacesContext.getCurrentInstance();
        if(file != null) {
            String ext = file.getFileName().substring(file.getFileName().lastIndexOf('.'), file.getFileName().length());
            if(".csv".equals(ext)) {
                parseFile();
            } else {
                context.addMessage(null, new FacesMessage("Selected username already exists"));
            }
        }
    }
    
    private void parseFile() {
        DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
        
        clearCalendar();
        try {
            CSVReader reader = new CSVReader(new InputStreamReader(file.getInputstream()), ',');
            String[] nextLine = reader.readNext();
            
            //throw away first line (column names)
            nextLine = reader.readNext();
            
            //order: id, title, startDate, endDate, Location *name*, isOutdoor, Badweatherlevel, isPublic, creatorName
            /*
            WARNING: at the moment column names are thrown away and the pairing 
            is hardcoded. this could be improved in the future.
            WARNING 2: Invitees are not supported
            */
            while(nextLine != null) {
                cb.setId(Long.parseLong(nextLine[0]));
                cb.setTitle(nextLine[1]);
                cb.setStartDate(df.parse(nextLine[2]));
                cb.setEndDate(df.parse(nextLine[3]));
                cb.setLocationName(nextLine[4]);
                cb.setOutdoor(Boolean.parseBoolean(nextLine[5]));
                cb.setBadWeatherLevel(Integer.parseInt(nextLine[6]));
                cb.setIsPublic(Boolean.parseBoolean(nextLine[7]));
                cb.setIsNewEvent(true);
                cb.setInvitees(null);
                cb.createEvent();
                nextLine = reader.readNext();
            }
        } catch (IOException ex) {
            Logger.getLogger(ImportExportBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ImportExportBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void clearCalendar() {
        cb.clearCalendar();
    }
 
    public List<Event> getEvents() {
        return events;
    }

    /**
     * @return the um
     */
    public UserManager getUm() {
        return um;
    }

    /**
     * @param um the cm to set
     */
    public void setUm(UserManager um) {
        this.um = um;
    }

    /**
     * @param events the events to set
     */
    public void setEvents(List<Event> events) {
        this.events = events;
    }

    /**
     * @return the file
     */
    public UploadedFile getFile() {
        return file;
    }

    /**
     * @param file the file to set
     */
    public void setFile(UploadedFile file) {
        this.file = file;
    }


}
